<!-- 组织架构同步页 -->
<template>
  <div class="org-structure-sync">
    <!-- 左侧部门树结构 -->
    <div class="left-panel">
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText"
        style="margin-bottom: 20px;"
      >
      </el-input>
      <el-tree
        :data="departmentTree"
        :props="defaultProps"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        ref="tree"
        default-expand-all
        highlight-current
      >
      </el-tree>
    </div>

    <!-- 右侧内容区域 -->
    <div class="right-panel">
      <!-- 查询表单 -->
      <el-form class="demo-form-inline" ref="formRef" :model="queryForm" label-width="100px" size="small" inline>
        <el-form-item label="客户经理名称" prop="managerName">
          <el-input v-model="queryForm.managerName" placeholder="客户经理名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" @click="resetData">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="el-row">
        <el-button type="info" icon="el-icon-coin" plain size="small" @click="syncData">数据同步</el-button>
        <el-button type="success" icon="el-icon-plus" plain size="small" @click="handleAdd">新增</el-button>
        <el-button type="danger" icon="el-icon-delete" plain size="small" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        height="100%"
        style="width: 100%; "
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" ></el-table-column>
        <el-table-column type="index" label="序号" width="50" ></el-table-column>
        <el-table-column prop="managerName" label="客户经理名称" ></el-table-column>
        <el-table-column prop="managerPhone" label="客户经理联系电话"></el-table-column>
        <el-table-column prop="department" label="部门"></el-table-column>
        <el-table-column prop="position" label="职位"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        style="text-align: right"
      ></el-pagination>

      <!-- 新增/编辑对话框 -->
      <OrgStructureSyncForm
        :visible.sync="dialogVisible"
        :dialogTitle="dialogTitle"
        :formData="form"
        @submit="handleSubmit"
      />

      <!-- 详情对话框 -->
      <OrgStructureSyncDetail
        :visible.sync="detailVisible"
        :formData="selectedRow"
      />
    </div>
  </div>
</template>

<script>
import OrgStructureSyncForm from './components/OrgStructureSyncForm.vue';
import OrgStructureSyncDetail from './components/OrgStructureSyncDetail.vue';

export default {
  name: "OrgStructureSync",
  components: { OrgStructureSyncForm, OrgStructureSyncDetail },
  data() {
    return {
      filterText: '',
      departmentTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryForm: {
        managerName: ""
      },
      totalTableData: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "",
      form: {},
      selectedRows: [],
      loading: false,
      detailVisible: false,
      selectedRow: {}
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    syncData() {
      this.loading = true;
      setTimeout(() => {
        // 模拟同步数据
        this.fetchData();
      }, 1000);
    },
    fetchData() {
      this.loading = true;
      setTimeout(() => {
        // 模拟接口请求数据
        this.totalTableData = this.generateRandomData(100); // 这里可以替换为实际的API调用
        const { managerName } = this.queryForm;
        const filteredData = this.totalTableData.filter(item => {
          return (
            (!managerName || item.managerName.includes(managerName))
          );
        });
        this.total = filteredData.length;
        this.tableData = filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.loading = false;
      }, 1000);
    },
    resetData() {
      this.$refs.formRef.resetFields()
      this.syncData()
    },
    handleAdd() {
      this.dialogTitle = "新增客户经理";
      this.form = {};
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑客户经理";
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleDetail(row) {
      this.selectedRow = row;
      this.detailVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该客户经理信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.indexOf(row);
        if (index > -1) {
          this.tableData.splice(index, 1);
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的客户经理信息!'
        });
        return;
      }
      this.$confirm('此操作将永久删除选中的客户经理信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(row => !this.selectedRows.includes(row));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    handleSubmit(formData) {
      if (this.dialogTitle === "新增客户经理") {
        this.totalTableData.unshift({ ...formData });
        this.tableData.unshift({ ...formData });
      } else {
        const index = this.tableData.findIndex(row => row.id === formData.id);
        if (index > -1) {
          this.$set(this.tableData, index, { ...formData });
        }
      }
      this.dialogVisible = false;
    },
    generateRandomData(count) {
      const departments = ["销售部", "市场部", "技术部", "人力资源部"];
      const positions = ["经理", "副经理", "专员", "助理"];
      const managerNames = ["张三", "李四", "王五", "赵六", "孙七"];
      const emails = ["zhangsan@example.com", "lisi@example.com", "wangwu@example.com", "zhaoliu@example.com", "sunqi@example.com"];

      const data = [];
      for (let i = 0; i < count; i++) {
        const id = i + 1;
        const managerName = managerNames[Math.floor(Math.random() * managerNames.length)];
        const managerPhone = `13${Math.floor(Math.random() * 900000000) + 100000000}`; // 随机生成手机号
        const department = departments[Math.floor(Math.random() * departments.length)];
        const position = positions[Math.floor(Math.random() * positions.length)];
        const email = emails[Math.floor(Math.random() * emails.length)];

        data.push({
          id,
          managerName,
          managerPhone,
          department,
          position,
          email
        });
      }
      return data;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      // 点击树节点时查询对应的部门客户经理数据
      console.log(data);
      // 模拟根据部门查询数据
      this.fetchDepartmentData(data.name);
    },
    fetchDepartmentData(departmentName) {
      this.loading = true;
      setTimeout(() => {
        // 模拟接口请求数据
        const departmentData = this.totalTableData.filter(item => item.department === departmentName);
        this.tableData = departmentData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.total = departmentData.length;
        this.loading = false;
      }, 1000);
    },
    generateDepartmentTree() {
      // 模拟生成部门树结构
      return [
        {
          id: 1,
          name: '销售部',
          children: [
            { id: 2, name: '销售一部' },
            { id: 3, name: '销售二部' }
          ]
        },
        {
          id: 4,
          name: '市场部',
          children: [
            { id: 5, name: '市场一部' },
            { id: 6, name: '市场二部' }
          ]
        },
        {
          id: 7,
          name: '技术部',
          children: [
            { id: 8, name: '技术一部' },
            { id: 9, name: '技术二部' }
          ]
        },
        {
          id: 10,
          name: '人力资源部'
        }
      ];
    }
  },
  mounted() {
    // 初始化加载部门树结构
    this.departmentTree = this.generateDepartmentTree();
  }
};
</script>

<style scoped lang="scss">
.org-structure-sync {
  display: flex;
  height: 100%;

  .left-panel {
    width: 15%;
    border-right: 1px solid #ebeef5;
    padding: 20px;
    box-sizing: border-box;
  }

  .right-panel {
    width: 85%;
    padding: 20px;
    box-sizing: border-box;

    .el-row {
      margin-bottom: 20px;
    }

    .el-table {
      margin-bottom: 20px;
    }
  }
}
</style>

